//
//  StartADView.m
//  lehuotest
//
//  Created by ice on 2017/1/9.
//  Copyright © 2017年 QF. All rights reserved.
//

#import "StartADView.h"

#define ADImageInfoUserDefaultsKey @"ADImageInfoUserDefaultsKey"

static NSString *const adImageUrl = @"adImageUrl";
static NSString *const adUrl = @"adUrl";
static NSString *const adStatue = @"adStatue";

@interface StartADView()

@property (nonatomic, strong) UIImageView *imgView;

@property (nonatomic, strong) UIButton *countBtn;

@property (nonatomic, strong) NSTimer *countTimer;

@property (nonatomic, assign) int count;

@property (nonatomic, strong) NSString *myUrlString;
@end
// 广告显示的时间
static int const showtime = 3;
@implementation StartADView
- (NSTimer *)countTimer
{
    if (!_countTimer) {
        _countTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
    }
    return _countTimer;
}
-(instancetype) init
{
    CGFloat w = [UIScreen mainScreen].bounds.size.width;
    CGFloat h = [UIScreen mainScreen].bounds.size.height;
    self = [super initWithFrame:CGRectMake(0, 0, w, h)];
    if (self){
        self.backgroundColor = [UIColor whiteColor];
        
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, w, h)];
        imgView.userInteractionEnabled = YES;
        imgView.clipsToBounds = YES;
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        [self addSubview:imgView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushToAd)];
        [imgView addGestureRecognizer:tap];
        self.imgView = imgView;

        
        // 2.跳过按钮
        CGFloat btnW = 60;
        CGFloat btnH = 30;
        _countBtn = [[UIButton alloc] initWithFrame:CGRectMake(w - btnW - 24, btnH, btnW, btnH)];
        [_countBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        [_countBtn setTitle:[NSString stringWithFormat:@"跳过%d", showtime] forState:UIControlStateNormal];
        _countBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_countBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _countBtn.backgroundColor = [UIColor colorWithRed:38 /255.0 green:38 /255.0 blue:38 /255.0 alpha:0.6];
        _countBtn.layer.cornerRadius = 4;
         [self addSubview:_countBtn];
        
        
    }
    return self;
}

//定时器方法
- (void)countDown
{
    _count --;
    [_countBtn setTitle:[NSString stringWithFormat:@"跳过%d",_count] forState:UIControlStateNormal];
    if (_count == 0) {
        
        [self dismiss];
    }
}



// 定时器倒计时
- (void)startTimer
{
    _count = showtime;
    [[NSRunLoop mainRunLoop] addTimer:self.countTimer forMode:NSRunLoopCommonModes];
}

// GCD倒计时
- (void)startCoundown
{
    __block int timeout = showtime + 1; //倒计时时间 + 1
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self dismiss];
                
            });
        }else{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [_countBtn setTitle:[NSString stringWithFormat:@"跳过%d",timeout] forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}


-(void) setFilePath:(NSString *)filePath urlString:(NSString *)urlString
{
//    _filePath = filePath;
    _imgView.image = [UIImage imageWithContentsOfFile:filePath];
    _myUrlString = urlString;
}

/**
 消失
 */
-(void)dismiss
{
    [self.countTimer invalidate];
    self.countTimer = nil;
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void) pushToAd
{
    NSLog(@"push");
    if (self.tapADViewBlock){
        self.tapADViewBlock(self.myUrlString);
    }
}
+(void) showWithTapBlock:(void(^)(NSString *urlString))success
{
    // 2.无论沙盒中是否存在广告图片，都需要重新调用广告接口，判断广告是否更新
    [StartADView requestGetAdImageInfo:^(NSDictionary *imageInfo) {
        if (!imageInfo[adImageUrl]){
            return ;
        }
        // 拼接沙盒路径
        NSString *imageName = [StartADView getImageNameByImageUrl:imageInfo[adImageUrl]];
        NSString *filePath = [StartADView getFilePathWithImageName:imageName];
        BOOL isExist = [StartADView isFileExistWithFilePath:filePath];
        if (!isExist){// 如果该图片不存在，则删除老图片，下载新图片
            [StartADView downloadAdImage:imageInfo];
        }else {
            [self showOldImageWithTapBlock:^(NSString *urlString) {
                success(urlString);
            }];
        }
    } failure:^{
        [self showOldImageWithTapBlock:^(NSString *urlString) {
            success(urlString);
        }];
    }];
}


/**
 显示缓存图片

 @param success success
 */
+(void) showOldImageWithTapBlock:(void(^)(NSString *urlString))success
{
    NSDictionary *imageInfo = [[NSUserDefaults standardUserDefaults] valueForKey:ADImageInfoUserDefaultsKey];
    
    NSString *imageName = [StartADView getImageNameByImageUrl:imageInfo[adImageUrl]];
    
    NSString *filePath = [StartADView getFilePathWithImageName:imageName];
    NSString *isShowAd = imageInfo[adStatue];
    NSString *urlString = imageInfo[adUrl];
    BOOL isExist = [StartADView isFileExistWithFilePath:filePath];
    if (isExist && isShowAd.intValue == 1) {// 图片存在
        StartADView *ad = [[StartADView alloc] init];
        ad.tapADViewBlock = ^(NSString *urlString){
            if (urlString){
                success(urlString);
            }
        };
        [ad setFilePath:filePath urlString:urlString];
        [ad startTimer];
        [[UIApplication sharedApplication].keyWindow addSubview:ad];
    }
}



/**
 网络请求广告接口

 @param success success
 @param failure failure
 */
+(void) requestGetAdImageInfo:(void(^)(NSDictionary *imageInfo))success failure:(void(^)())failure
{
    // TODO 请求广告接口
    NSArray *imageArray = @[@"http://imgsrc.baidu.com/forum/pic/item/9213b07eca80653846dc8fab97dda144ad348257.jpg", @"http://pic.paopaoche.net/up/2012-2/20122220201612322865.png", @"http://img5.pcpop.com/ArticleImages/picshow/0x0/20110801/2011080114495843125.jpg", @"http://www.mangowed.com/uploads/allimg/130410/1-130410215449417.jpg"];
    NSString *imageUrl =imageArray[0];// imageArray[arc4random() % imageArray.count];
    NSString *isShow = @"1";
    NSString *urlString = @"http://www.baidu.com";
    
    
    NSMutableDictionary *dic =[NSMutableDictionary dictionary];
    [dic setObject:imageUrl forKey:adImageUrl];
    [dic setObject:isShow forKey:adStatue];
    [dic setObject:urlString forKey:adUrl];
    
    success(dic);
}

/**
 *  下载新图片
 */
+ (void)downloadAdImage:(NSDictionary *)imageInfo
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *imageUrl = imageInfo[adImageUrl];
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
        UIImage *image = [UIImage imageWithData:data];
        
        NSString *imageName = [StartADView getImageNameByImageUrl:imageUrl];
        
        BOOL isShow = imageInfo[adStatue];
        
        NSString *urlString = imageInfo[adUrl];
        
        NSString *filePath = [StartADView getFilePathWithImageName:imageName]; // 保存文件的名称
        
        if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) {// 保存成功
            NSLog(@"保存成功");
            [StartADView deleteOldImage];
            NSMutableDictionary *dic =[NSMutableDictionary dictionary];
            [dic setObject:imageUrl forKey:adImageUrl];
            [dic setObject:@(isShow) forKey:adStatue];
            [dic setObject:urlString forKey:adUrl];
            [[NSUserDefaults standardUserDefaults] setValue:dic forKey:ADImageInfoUserDefaultsKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            // 如果有广告链接，将广告链接也保存下来
        }else{
            NSLog(@"保存失败");
        }
        
    });
}
/**
 *  删除旧图片
 */
+ (void)deleteOldImage
{
    NSDictionary *imageInfo = [[NSUserDefaults standardUserDefaults] valueForKey:ADImageInfoUserDefaultsKey];
    NSString *imageUrl = imageInfo[adImageUrl];
    
    NSString *imageName = [StartADView getImageNameByImageUrl:imageUrl];
    if (imageName) {
        NSString *filePath = [StartADView getFilePathWithImageName:imageName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:filePath error:nil];
    }
}


/**
 获取图片名称
 */
+(NSString *)getImageNameByImageUrl:(NSString *)imageUrl
{
    NSArray *stringArr = [imageUrl componentsSeparatedByString:@"/"];
    NSString *imageName = stringArr.lastObject;
    return imageName;
}

/**
 *  根据图片名拼接文件路径
 */
+ (NSString *)getFilePathWithImageName:(NSString *)imageName
{
    if (imageName) {
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        
        return filePath;
    }
    
    return nil;
}

/**
 *  判断文件是否存在
 */
+ (BOOL)isFileExistWithFilePath:(NSString *)filePath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = FALSE;
    return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
